package com.idp.web.security.provider;

import com.idp.common.token.SysUserAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * web端用户名密码登录
 * @author king
 */
@Component
public class SysUserAuthenticationProvider implements AuthenticationProvider {

    @Qualifier("SysUserDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());
        String password = authentication.getCredentials().toString();
        String encodedPassword = userDetails.getPassword();

        if(!passwordEncoder.matches(password, encodedPassword)) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        return new SysUserAuthenticationToken(userDetails, authentication.getCredentials().toString(), userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(SysUserAuthenticationToken.class);
    }
}
